//
//  ConfirmOrderViewController.swift
//  ShopIOS
//
//  Created by Apple on 2019/7/30.
//  Copyright © 2019 Apple. All rights reserved.
//

import UIKit
//确认订单页面
class ConfirmOrderViewController: UIViewController{
    @IBOutlet weak var uv_back: UIView!
    @IBOutlet weak var usv_add: UIStackView!
    @IBOutlet weak var uv_add: UIView!
    @IBOutlet weak var name: UILabel!
    @IBOutlet weak var phone: UILabel!
    @IBOutlet weak var address: UILabel!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var lb_total: UILabel!
    @IBOutlet weak var lb_submit: UILabel!
    @IBOutlet weak var uv_top: UIView!
    var sku:mSkuArray!
    var cartItemIds:String!
    var submitModel:SubmitModel!
    var dataSource:[SubmitModelProducts]!
    var cartItemModels:[SubmitModelCartItemModels]!
    var addressid:String!
    init(sku:mSkuArray?,cartItemIds:String?){//第一个参数立即购买提交 第二个参数购物车提交
        super.init(nibName: nil, bundle: nil)
        self.sku=sku
        self.cartItemIds=cartItemIds
        if (self.sku != nil) {
            getSubmitModel()
        }else{
            getSubmitByCartModel()
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        uv_top.layer.cornerRadius=10
        tableView.dataSource=self
        tableView.delegate=self
        tableView.separatorStyle = .none
        tableView.register(UINib(nibName: "ConfirmOrderTableViewCell", bundle: nil), forCellReuseIdentifier: "re")
        tableView.register(UINib(nibName: "ConfirmOrderHeaderView", bundle: nil),forHeaderFooterViewReuseIdentifier: "head")
        tableView.register(UINib(nibName: "ConfirmOrderFooterView", bundle: nil), forHeaderFooterViewReuseIdentifier: "foot")
        tableView.backgroundColor="#E9E9E9".color()
        uv_back.addOnClickListener(target: self, action: #selector(back))
        uv_add.addOnClickListener(target: self, action: #selector(addaddr))
        usv_add.addOnClickListener(target: self, action: #selector(addaddr))
        if (self.sku != nil) {
            lb_submit.addOnClickListener(target: self, action: #selector(postSubmitOrder))
        }else{
            lb_submit.addOnClickListener(target: self, action: #selector(postSubmitOrderByCart))
        }
        NotificationCenter.default.addObserver(self, selector: #selector(update), name: NSNotification.Name("choose"), object: nil)
        // Do any additional setup after loading the view.
    }
    @objc func showPop(){
        let popview = ZXPopView.init(frame: self.view.bounds)
        let payview=Bundle.main.loadNibNamed("PayWayView", owner: nil, options: nil)?[0]as!PayWayView
        payview.uv_wallet.layer.cornerRadius=10
        payview.uv_wallet.layer.maskedCorners=CACornerMask(rawValue: CACornerMask.layerMinXMinYCorner.rawValue|CACornerMask.layerMaxXMinYCorner.rawValue)
        payview.uv_wechat.layer.cornerRadius=10
        payview.uv_wechat.layer.maskedCorners=CACornerMask(rawValue: CACornerMask.layerMinXMaxYCorner.rawValue|CACornerMask.layerMaxXMaxYCorner.rawValue)
        payview.uv_cancel.layer.cornerRadius=10
        popview.contenView = payview
        popview.showInView(view: self.view)
    }
    @objc func update(noti: Notification){
        let addr=noti.object as!mShippingAddress
        addressid=String(addr.Id)
        name.text=addr.ShipTo!
        phone.text=addr.Phone!
        address.text="\(addr.RegionFullName!)\(addr.Address!)"
    }
    @objc func addaddr(){
        self.navigationController?.pushViewController(AddressViewController(choose: true), animated: true)
    }
    @objc func back(){
        self.navigationController?.popViewController(animated: true)
    }
    func getSubmitModel(){
        var d = ["userkey":userkey,
                 "skuId":sku.SkuId!,
                 "count":sku.count,
                 "app_key":app_key,
                 "timestamp":getTimestamp()
            ] as! [String : String]
        let sign=SignTopRequest(params: d)
        d["sign"]=sign
        AlamofireHelper.get(url: GetSubmitModel, parameters: d, successHandler: {[weak self](res)in
            HUD.dismiss()
            guard let ss = self else {return}
            ss.submitModel = SubmitModel.init(json: res)
            ss.addressid=String(ss.submitModel.Address!.Id)
            ss.name.text=ss.submitModel.Address?.ShipTo!
            ss.phone.text=ss.submitModel.Address?.Phone!
            ss.address.text=ss.submitModel.Address?.Address!
            ss.dataSource = ss.submitModel.products
            ss.lb_total.text="合计：￥\(ss.submitModel.TotalAmount)"
            ss.tableView.reloadData()
        }){[weak self] (error) in
            HUD.dismiss()
            guard let ss = self else {return}
        }
    }
    func getSubmitByCartModel(){
        var d = ["userkey":userkey,
                 "cartItemIds":cartItemIds,
                 "app_key":app_key,
                 "timestamp":getTimestamp()
            ] as! [String : String]
        let sign=SignTopRequest(params: d)
        d["sign"]=sign
        AlamofireHelper.get(url: GetSubmitByCartModel, parameters: d, successHandler: {[weak self](res)in
            HUD.dismiss()
            guard let ss = self else {return}
            ss.submitModel = SubmitModel.init(json: res)
            ss.addressid=String(ss.submitModel.Address!.Id)
            ss.name.text=ss.submitModel.Address?.ShipTo!
            ss.phone.text=ss.submitModel.Address?.Phone!
            ss.address.text=ss.submitModel.Address?.Address!
            ss.dataSource = ss.submitModel.products
            ss.lb_total.text="合计：￥\(ss.submitModel.TotalAmount)"
            ss.tableView.reloadData()
        }){[weak self] (error) in
            HUD.dismiss()
            guard let ss = self else {return}
        }
    }
    @objc func postSubmitOrder(){
        if (addressid == nil){
            HUD.showText("请添加收货地址！")
        }
        var d = ["userkey":userkey,
                 "skuIds":sku.SkuId!,
                 "counts":sku.count,
                 "recieveAddressId":addressid,
                 "couponIds":"",
                 "integral":"0",
                 "isCashOnDelivery":"false",//是否为货到付款
                 "invoiceType":"0",//0不需要发票 2普通发票
                 "invoiceContext":"",//发票内容
                 "invoiceTitle":"",//发票抬头
                 "orderRemarks":"",//订单备注，多订单，号分割
                 "app_key":app_key,
                 "timestamp":getTimestamp()
            ] as! [String : String]
        let sign=SignTopRequest(params: d)
        d["sign"]=sign
        AlamofireHelper.post(url: PostSubmitOrder, parameters: d, successHandler: {[weak self](res)in
            HUD.dismiss()
            guard let ss = self else {return}
        }){[weak self] (error) in
            HUD.dismiss()
            guard let ss = self else {return}
        }
    }
    @objc func postSubmitOrderByCart(){
        if (addressid == nil){
            HUD.showText("请添加收货地址！")
        }
        var d = ["userkey":userkey,
                 "cartItemIds":cartItemIds,
                 "recieveAddressId":addressid,
                 "couponIds":"",
                 "integral":"0",
                 "isCashOnDelivery":"false",
                 "invoiceType":"0",
                 "invoiceContext":"",
                 "invoiceTitle":"",
                 "orderRemarks":"",
                 "app_key":app_key,
                 "timestamp":getTimestamp()
            ] as! [String : String]
        let sign=SignTopRequest(params: d)
        d["sign"]=sign
        AlamofireHelper.post(url: PostSubmitOrderByCart, parameters: d, successHandler: {[weak self](res)in
            HUD.dismiss()
            guard let ss = self else {return}
        }){[weak self] (error) in
            HUD.dismiss()
            guard let ss = self else {return}
        }
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
extension ConfirmOrderViewController:UITableViewDataSource,UITableViewDelegate{
    func numberOfSections(in tableView: UITableView) -> Int {
        return dataSource==nil ? 0 : dataSource.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        cartItemModels=dataSource[section].CartItemModels
        return cartItemModels.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell=tableView.dequeueReusableCell(withIdentifier: "re") as! ConfirmOrderTableViewCell
        let cartItem = cartItemModels[indexPath.row]
        cell.selectionStyle = .none
        cell.icon.setImage(path: URL.init(string: cartItem.imgUrl!)!)
        cell.name.text = cartItem.name
        cell.price.text = "￥\(cartItem.price)"
        cell.count.text = "x\(cartItem.count)"
        return cell
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let headview=tableView.dequeueReusableHeaderFooterView(withIdentifier: "head") as! ConfirmOrderHeaderView
        let sec=dataSource[section]
        headview.lb_shopname.text=sec.ShopName
        return headview
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footview=tableView.dequeueReusableHeaderFooterView(withIdentifier: "foot") as! ConfirmOrderFooterView
        footview.uv_footer.layer.cornerRadius=10
        footview.uv_footer.layer.maskedCorners=CACornerMask(rawValue: CACornerMask.layerMinXMaxYCorner.rawValue|CACornerMask.layerMaxXMaxYCorner.rawValue)
        let sec=dataSource[section]
        let money = String("￥\(sec.ShopTotal)")
        let hintString = NSMutableAttributedString(string: "共\(sec.CartItemModels.count)件商品 小计："+money)
        //获取要调整颜色的文字位置,调整颜色
        let range: NSRange = (hintString.string as NSString).range(of:money)
        hintString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red, range: range)
        footview.lb_total.attributedText = hintString
        return footview
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 170
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 50
    }
    func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        view.corner(byRoundingCorners: [.topLeft,.topRight], radii: 10)
    }
//    func tableView(_ tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
//        view.corner(byRoundingCorners: [.allCorners], radii: 10)
//    }
}
